﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.UI.WebControls;
using System.Web.UI;
using System.Web;
using System.Web.UI.HtmlControls;

namespace Beetle.Web.UI.WebControls
{
    /// <summary>
    /// Web 条件组合控件
    /// </summary>
    /// <!-- 作者:韦腾  时间:2010年02月10日 -->
    [ParseChildren(true, "Items")]
    public partial class SearchView : CompositeControl, IPostBackDataHandler
    {
        internal const string ValueSplitStr = "|{[]}|";
        private SearchItemCollection items = null;
        private CustomValidator customValidator = null;

        [PersistenceMode(PersistenceMode.InnerDefaultProperty)]
        public SearchItemCollection Items
        {
            get
            {
                if (this.items == null)
                {
                    this.items = new SearchItemCollection(this);
                }

                return this.items;
            }
        }


        public SearchValueItemCollection Values { get; private set; }

        public SearchModeEnum SearchMode
        {
            get
            {
                object o = ViewState["SearchMode"];
                return o != null ? (SearchModeEnum)o : SearchModeEnum.Simple;
            }

            set
            {
                ViewState["SearchMode"] = value;
            }
        }

        public SearchView()
        {
            this.Values = new SearchValueItemCollection();

            this.customValidator = new CustomValidator();
            this.customValidator.ServerValidate += new ServerValidateEventHandler(customValidator_ServerValidate);
        }

        void customValidator_ServerValidate(object source, ServerValidateEventArgs args)
        {
        }

        protected override void CreateChildControls()
        {
            base.CreateChildControls();
            this.Controls.Clear();
            this.ChildControlsCreated = true;
            this.customValidator.ID = "CSVD";
            string innerHTML = string.Empty;

            List<SearchItemBase> itemsTemp = new List<SearchItemBase>();

            if (this.Values.Count == 0)
            {
                for (int i = 0; i < this.Items.Count; i++)
                {
                    if (this.Items[i].IsSelect)
                    {
                        SearchItemBase itemTemp = (SearchItemBase)this.Items[i].Clone();
                        itemsTemp.Add(itemTemp);

                        if (this.SearchMode == SearchModeEnum.Simple)
                        {
                            break;
                        }
                    }
                }
            }
            else
            {
                foreach (SearchValueItem value in this.Values)
                {
                    SearchItemBase itemTemp = (SearchItemBase)this.Items[value.ItemIndex].Clone();
                    itemTemp.DefaultOperation = value.SearchOperation;
                    itemTemp.DefaultPredication = value.Predication;
                    itemTemp.DefaultValue = value.Value;
                    itemsTemp.Add(itemTemp);
                }
            }

            for (int i = 0; i < itemsTemp.Count; i++)
            {
                itemsTemp[i].Owner = this;

                System.Text.StringBuilder sb = new StringBuilder();
                System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(new System.IO.StringWriter(sb));

                itemsTemp[i].Render(htw, i == itemsTemp.Count - 1);
                string itemHtml = sb.ToString();
                innerHTML += itemHtml;
            }

            innerHTML = "<table id=\"" + this.ClientID + "_MainTable\"><tbody>" + innerHTML + "</tbody></table>";
            this.Controls.Add(new LiteralControl(innerHTML));

            this.Controls.Add(this.customValidator);
        }

        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);
            this.Page.RegisterRequiresPostBack(this);
            Helper.RegisterWebFormsScript(this.Page);

            for (int i = 0; i < this.Items.Count; i++)
            {
                System.Text.StringBuilder sb = new StringBuilder();
                System.Web.UI.HtmlTextWriter htw = new System.Web.UI.HtmlTextWriter(new System.IO.StringWriter(sb));

                this.Items[i].Render(htw, true);
                string itemHtml = sb.ToString();
                this.Page.ClientScript.RegisterExpandoAttribute(this.ClientID, "itemhtml_" + i.ToString(), itemHtml.Replace("\r\n", "").Replace("\t", ""));
            }
        }

        protected override void AddAttributesToRender(HtmlTextWriter writer)
        {
            base.AddAttributesToRender(writer);
        }

        #region IPostBackDataHandler 成员

        public bool LoadPostData(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            this.ParseValues(postDataKey, postCollection);
            return true;
        }

        private void ParseValues(string postDataKey, System.Collections.Specialized.NameValueCollection postCollection)
        {
            string connectionsStr = postCollection[postDataKey + SearchItemBase.ConnectionsSelectExtName];
            string fieldSelectsStr = postCollection[postDataKey + SearchItemBase.FieldsSelectExtName];
            string operationsStr = postCollection[postDataKey + SearchItemBase.OperationsSelectExtName];
            string valuesSelectStr = postCollection[postDataKey + SearchItemBase.ValuesExtName];
            string infosStr = postCollection[postDataKey + SearchItemBase.ItemInfosExtName];

            string[] connections = connectionsStr.Split(new char[] { ',' });
            string[] fieldSelects = fieldSelectsStr.Split(new char[] { ',' });
            string[] operations = operationsStr.Split(new char[] { ',' });
            string[] infos = infosStr.Split(new char[] { ',' });
            string[] valuesTemp = valuesSelectStr.Split(new string[] { SearchView.ValueSplitStr }, StringSplitOptions.None);
            string[] values = new string[valuesTemp.Length - 1];

            for (int i = 0; i < values.Length; i++)
            {
                if (!string.IsNullOrEmpty(valuesTemp[i + 1]) && valuesTemp[i + 1].Length > 1)
                {
                    values[i] = valuesTemp[i + 1].Substring(1, valuesTemp[i + 1].Length - 2);
                }
                else
                {
                    values[i] = string.Empty;
                }
            }

            if (connections.Length != fieldSelects.Length ||
                connections.Length != operations.Length ||
                connections.Length != infos.Length ||
                connections.Length != values.Length)
            {
                throw new Exception("SearchView 返回数据异常");
            }


            this.Values.Clear();

            for (int i = 0; i < connections.Length; i++)
            {
                SearchValueItem svi = new SearchValueItem();
                string[] infoItems = infos[i].Split(new char[] { '|' });

                svi.DataType = (SearchDateType)Enum.Parse(typeof(SearchDateType), infoItems[2]);
                svi.FieldName = fieldSelects[i];
                svi.ItemIndex = int.Parse(infoItems[3]);
                svi.ItemType = this.Items[svi.ItemIndex].GetType();
                if (i < connections.Length - 1)
                {
                    svi.Predication = (SearchPredicationEnum)Enum.Parse(typeof(SearchPredicationEnum), connections[i]);
                }
                svi.SearchOperation = (SearchOperationEnum)Enum.Parse(typeof(SearchOperationEnum), operations[i]);
                svi.Value = values[i];

                this.Values.Add(svi);
            }
        }

        public void RaisePostDataChangedEvent()
        {

        }

        #endregion
    }
}
